package com.thoughtworks.studio.tools.cardkit.generator;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.log4j.Logger;

import com.thoughtworks.studio.tools.cardkit.Card;
import com.thoughtworks.studio.tools.cardkit.CardMetrics;
import com.thoughtworks.studio.tools.graphics.ImageGenerator;

public class CardImageGenerator {
	 private Logger logger= Logger.getLogger(CardImageGenerator.class);
	private String path = "D:\\CardImage";
	private String imgType = "JPEG";

	private ImageGenerator creator;

	public CardImageGenerator(ImageGenerator imageGenerator) {
		this.creator = imageGenerator;
	}

	public void generate(Card card) {
		BufferedImage image = creator.createImage(CardMetrics.cardProperty);
		Graphics g = image.getGraphics();
		decorateBackground(g);
		drawNumber(g, card);
		drawName(g, card);
		g.dispose();
		output(image, card, imgType);
	}

	private void output(BufferedImage image, Card card, String imgType) {
		try {
			File dirFile = new File(path);
			if (dirFile.exists() && dirFile.isDirectory()) {
				logger.debug("The folder exists.");
			} else {
				logger.info("The folder do not exist,now trying to create a one...");
				if (dirFile.mkdir()) {
					logger.info("Create successfully!");
				} else {
					logger.warn("Disable to make the folder,please check the disk is full or not.");
					System.exit(1);
				}
			}
			creator.outputImage(image, path + "\\" + card.getNumber() + ".jpg",
					imgType);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private void drawNumber(Graphics g, Card card) {
		creator.drawText(g, card.getNumber(), CardMetrics.numberProperty
				.getFont(), CardMetrics.numberProperty.getColor(),
				CardMetrics.numberProperty.getPointX(),
				CardMetrics.numberProperty.getPointY(), false);
		System.out.println(card.getNumber());

	}

	private void drawName(Graphics g, Card card) {
		creator.drawText(g, card.getName(), CardMetrics.nameProperty
				.getFont(), CardMetrics.nameProperty.getColor(),
				CardMetrics.nameProperty.getPointX(), CardMetrics.nameProperty
						.getPointY(), true);
	}

	private void decorateBackground(Graphics g) {
		creator.fillBackground(g);
		creator.drawFrame(g);
	}
}
